/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.demo.widget;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.mol.market.R;
import com.mol.market.common.widget.LoadingDrawable;
import com.mol.market.ui.core.LazyLoadAdapter;

/**
 * 实现的延迟加载的AbsListView<hr>
 * 封装了EmptyView和FooterView，如果修改EmptyView或者FooterView，务必修改这两个View的相关逻辑,具体应该
 * 修改以下三个方法.<br>
 * {@link #showEmptyViewWhenLoadFail()} , {@link #showFooterViewByState(View, FooterViewState)},
 * {@link #onClick(View)}
 * <br>
 * 子类不必要实现 {@link OnClickListener},只需要<strong>Override</strong> {@link #onClick(View)}方法
 * <br>
 * <strong>子类需要自己实现相关业务逻辑</strong>
 * @author Chaos	
 * @Description 延迟加载的ListFragment
 * @date 2012-12-12 
 */
public abstract class LazyLoadListFragment extends LazyLoadAbsListViewFragment
                implements OnClickListener{
    
    /**
     * 每一页加载多少个
     */
    private int mItemsPerPage = 20;

    /**
     * 一共有多少个
     */
    private int mTotalSize = 0;

    /**
     * 是否获得总条目数
     */
    private boolean mHasTotalSize;

    public boolean isHasTotalSize() {
        return mHasTotalSize;
    }

    public final int getStart(){
        return getLazyLoadCount() * mItemsPerPage;
    }
    
    public final int getEnd(){
        return getStart() + getSize();
    }
    
    public final int getSize(){
        return mItemsPerPage;
    }
    
    public final void setTotal(int size){
        this.mTotalSize = size;
        this.mHasTotalSize = true;
        closeLazyloadIfNeed(size);
    }
    
    /**
     * 如果总数量不足一页，则关闭延迟加载功能。
     */
    private void closeLazyloadIfNeed(int totalSize){
        
        LazyLoadAdapter adapter = getAdapter();
        
        if(adapter == null){
            //no need to change
            return ;
        }

        if (totalSize <= getSize()) {
            adapter.closeLazyLoad();
        } else {
            adapter.openLazyLoad();
        }
    }
    
    public final void setItemPageCount(int itemPageCount){
        this.mItemsPerPage = itemPageCount;
    }
    
    /**
     * 复写此方法的同时必须复写
     * {@link #showFooterViewByState(View, FooterViewState)} 
     */
    @Override
    protected View initFooterView(LayoutInflater inflater) {
        View mFooterView = inflater.inflate(R.layout.footer_loading, null, false);
        mFooterView.setBackgroundResource(R.drawable.list_item_bg_selector);
        mFooterView.setVisibility(View.GONE);
        return mFooterView;
    }

    @Override
    protected boolean hasMore(int nowLazyLoadCount) {
        return nowLazyLoadCount * mItemsPerPage < mTotalSize;
    }

    private ProgressBar mLoading;
    private View        mNoNetWork;
    private Button      mRetry;
    @Override
    protected View initEmptyView(LayoutInflater inflater, View ancestor,
            Bundle savedInstanceState) {
        View emptyView = ancestor.findViewById(R.id.loading);
        mLoading = (ProgressBar) emptyView.findViewById(R.id.progressbar);
        mLoading.setIndeterminateDrawable(new LoadingDrawable(getActivity()));
        mNoNetWork = emptyView.findViewById(R.id.no_network);
        mRetry     = (Button) mNoNetWork.findViewById(R.id.btn_no_network);
        mRetry.setOnClickListener(this);
        emptyView.setVisibility(View.VISIBLE);
        mLoading.setVisibility(View.VISIBLE);
        mNoNetWork.setVisibility(View.GONE);
        return emptyView;
    }

    private ProgressBar mFooterProgressBar;
    private TextView    mFooterHint;
    @Override
    protected void showFooterViewByState(View footerView, FooterViewState state) {
        if(footerView != null){
            if(!isInit()){
                mFooterProgressBar = (ProgressBar) footerView.findViewById(R.id.f_progressbar);
                mFooterProgressBar.setIndeterminateDrawable(new LoadingDrawable(getActivity()));
                mFooterProgressBar.setVisibility(View.VISIBLE);
                mFooterHint = (TextView) footerView.findViewById(R.id.f_no_data);
                mFooterHint.setOnClickListener(this);
                mFooterHint.setVisibility(View.INVISIBLE);
            }
            switch (state) {
            case LOADING:
                footerView.setVisibility(View.VISIBLE);
                mFooterProgressBar.setVisibility(View.VISIBLE);
                mFooterHint.setVisibility(View.GONE);
                break;
            case FAIL:
                footerView.setVisibility(View.VISIBLE);
                mFooterProgressBar.setVisibility(View.GONE);
                mFooterHint.setVisibility(View.VISIBLE);
                break;
            case OVER:
                if(getAdapter() != null){
                    getAdapter().closeLazyLoad();
                }
                footerView.setVisibility(View.GONE);
                removeFooter(footerView);
                break;
            case SUCCESS:
                footerView.setVisibility(View.GONE);
                break;
            }
        }
    }
    
    private boolean isInit(){
        return mFooterProgressBar != null && mFooterHint != null;
    }

    /**
     * 子类若Override的此方法，应该首先调用
     * <code>super.onClick(View) </code>
     */
    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.f_no_data){
            showFooterViewByState(getFooterView(), FooterViewState.LOADING);
            doLazyLoad();
        }else if(v.getId() == R.id.btn_no_network){
            mLoading.setVisibility(View.VISIBLE);
            mNoNetWork.setVisibility(View.GONE);
            doLazyLoad();
        }
    }

    @Override
    protected void showEmptyViewWhenLoadFail() {
        mLoading.setVisibility(View.GONE);
        mNoNetWork.setVisibility(View.VISIBLE);
    }
    
    

    @Override
    protected void dealloc() {
        mItemsPerPage      = 0;
        mTotalSize         = 0;
        mFooterHint        = null;
        mFooterProgressBar = null;
        mNoNetWork         = null;
        mLoading           = null;
        mRetry             = null;
        mHasTotalSize      = false;
        super.dealloc();
    }

    @Override
    protected View initHeaderView(LayoutInflater inflater) {
        return null;
    }
    
    @Override
    protected void reset() {
        mTotalSize = 0;
        
        if(getAbsListView() != null && getAbsListView() instanceof ListView){
            ListView list = (ListView) getAbsListView();
            if (list.getFooterViewsCount() == 0) {
                list.addFooterView(getFooterView(), null, false);
            }
        }
        
        //fix bug by Chaos at 2013/2/26
        //重置Loading动画,修复loading不显示的bug.
        showFooterViewByState(getFooterView(), FooterViewState.LOADING);
        
        super.reset();
    }
}
